/** 本地缓存对象: storage
 * 基于 common.js
 */
(function (root, factory) {
  if (typeof exports === 'object') {
    module.exports = factory(require('common'));
  } else if (typeof define === 'function' && define.amd) {
    define(['common'], factory);
  } else {
    root.storage = factory(root.common);
  }
})(this, function (common) {
  const { ENV, const: constant, cache_keys } = common;

  const storage = {
    prefix_key: constant.MODULE_KEY + '_' + ENV + '_',
    default_type: 'local',
    setItem: function (key, value, type = null) {
      if (type === null) {
        type = this.default_type;
      }
      if (type === 'local') {
        this.setLocal(key, value);
      } else {
        this.setSession(key, value);
      }
    },
    getItem: function (key, type = null) {
      if (type === null) {
        type = this.default_type;
      }
      if (type === 'local') {
        return this.getLocal(key);
      } else {
        return this.getSession(key);
      }
    },
    removeItem: function (key, type = null) {
      if (type === null) {
        type = this.default_type;
      }
      if (type === 'local') {
        this.removeLocal(key);
      } else {
        this.removeSession(key);
      }
    },
    setLocal: function (key, value, expire = null) {
      const data = {
        value,
        expireTime: expire !== null ? Date.now() + expire * 1000 : null,
      };
      localStorage.setItem(this.prefix_key + key, JSON.stringify(data));
    },
    getLocal: function (key) {
      let data = localStorage.getItem(this.prefix_key + key);
      if (data) {
        data = JSON.parse(data);
        if (data.expireTime === null || data.expireTime > Date.now()) {
          return data.value;
        }
        this.removeLocal(key);
      }
      return void 0;
    },
    removeLocal: function (key) {
      localStorage.removeItem(this.prefix_key + key);
    },
    setSession: function (key, value, expire = null) {
      const data = {
        value,
        expireTime: expire !== null ? Date.now() + expire * 1000 : null,
      };
      sessionStorage.setItem(this.prefix_key + key, JSON.stringify(data));
    },
    getSession: function (key) {
      let data = sessionStorage.getItem(this.prefix_key + key);
      if (data) {
        data = JSON.parse(data);
        if (data.expireTime === null || data.expireTime > Date.now()) {
          return data.value;
        }
        this.removeSession(key);
      }
      return void 0;
    },
    removeSession: function (key) {
      sessionStorage.removeItem(this.prefix_key + key);
    },
  };

  storage.setLocal(cache_keys.RANDOM_DES_KEY, constant.DEFAULT_DES_KEY);
  storage.setLocal(cache_keys.RANDOM_AES_KEY, constant.DEFAULT_AES_KEY);

  // 暴露方法
  return storage;
});
